import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:my_audio_recorder/my_audio_recorder.dart';
import 'package:my_audio_recorder_example/Bean/AudioRecordItem.dart';
import 'package:my_audio_recorder_example/Ext/StringExt.dart';
import 'package:my_audio_recorder_example/Util/GlobalTimer.dart';

import '../Util/ObjectBox.dart';

/// 录音页
class RecordPage extends StatefulWidget {
  const RecordPage({super.key});

  @override
  State<StatefulWidget> createState() => _RecordPage();
}

class _RecordPage extends State<RecordPage> {
  int currentState = RecordState.RECORD_READY;

  // 录音plugin
  final _myAudioRecorderPlugin = MyAudioRecorder();

  int seconds = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('录音'),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                '录音时长',
                style: TextStyle(fontSize: 24),
              ),
              seconds != 0
                  ? Text(GlobalTimer.formatDuration(seconds))
                  : SizedBox(
                      height: 0,
                    ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: () {
                  if (currentState == RecordState.RECORDING) {
                    '已在录音~'.toastError(context);
                    return;
                  }

                  /// 开始录音
                  startRecord();
                },
                child: Text('开始'),
              ),
              SizedBox(height: 10),
              ElevatedButton(
                  onPressed: () {
                    if (currentState == RecordState.RECORDING) {
                      /// 暂停录音
                      pauseRecord();
                    } else {
                      /// 继续录音
                      continueRecord();
                    }
                  },
                  child: Text('继续/暂停')),
              SizedBox(height: 10),
              ElevatedButton(
                onPressed: () {
                  /// 结束录音
                  stopRecord();
                },
                child: Text('结束'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 开始录音
  Future<void> startRecord() async {
    String res;
    try {
      res = await _myAudioRecorderPlugin.startRecord() ?? '';
    } on PlatformException {
      res = '';
    }
    if (!mounted) return;
    setState(() {
      // 更新状态
      if (res != '') {
        currentState = RecordState.RECORDING;
        res.toastSuccess(context);
        GlobalTimer().startTimer();
        GlobalTimer().timerStream.listen((int elapsedSeconds) {
          // 更新页面等...
          setState(() {
            seconds = elapsedSeconds;
          });
        });
      }
    });
  }

  /// 继续录音
  Future<void> continueRecord() async {
    if (currentState == RecordState.RECORD_READY) {
      '请先开始录音~'.toastError(context);
      return;
    }
    String res;
    try {
      res = await _myAudioRecorderPlugin.continueRecord() ?? '';
    } on PlatformException {
      res = '';
    }
    if (!mounted) return;
    setState(() {
      // 更新状态
      if (res != '') {
        currentState = RecordState.RECORDING;
        res.toastSuccess(context);
        // 继续录音，计时恢复
        GlobalTimer().resumeTimer();
      }
    });
  }

  /// 暂停录音
  Future<void> pauseRecord() async {
    if (currentState == RecordState.RECORD_READY) {
      '请先开始录音~'.toastError(context);
      return;
    }
    String res;
    try {
      res = await _myAudioRecorderPlugin.pauseRecord() ?? '';
    } on PlatformException {
      res = '';
    }
    if (!mounted) return;
    setState(() {
      // 更新状态
      if (res != '') {
        currentState = RecordState.RECORD_PAUSE;
        res.toastSuccess(context);
        // 暂停录音，计时停止
        GlobalTimer().pauseTimer();
      }
    });
  }

  /// 停止录音
  Future<void> stopRecord() async {
    String res;
    try {
      res = await _myAudioRecorderPlugin.stopRecord() ?? '';
    } on PlatformException {
      res = '';
    }
    if (!mounted) return;
    setState(() {
      // 更新状态
      if (res != '') {
        // res 为路径
        // 结束录音，计时重置
        GlobalTimer().stopTimer();
        String name =
            res.substring(res.lastIndexOf('/') + 1, res.lastIndexOf('.'));
        String filePath = res;
        int duration = seconds;
        String time = GlobalTimer.formatDuration(seconds);
        '录音名称：$name\n文件路径：\n$filePath\n总时长(S)：$duration\n格式化时长(S)：$time'
            .toastSuccess(context);
        print(
            '录音结果：\n录音名称：$name\n文件路径：\n$filePath\n总时长(S)：$duration\n格式化时长(S)：$time');

        /// 进行数据的存储
        final recordData = AudioRecordItem();
        recordData.name = name;
        recordData.duration = duration;
        recordData.filePath = filePath;
        recordData.time = time;
        recordData.createTime = DateTime.now().toString();
        var rid = saveOrUpdate(recordData);
        print('录音保存结果：id：$rid');
        currentState = RecordState.RECORD_READY;
        setState(() {
          seconds = 0;
        });

        /// 退出页面，刷新录音结果
        Navigator.pop(context, true);
      }
    });
  }
}

class RecordState {
  static final int RECORD_READY = 1;
  static final int RECORDING = 2;
  static final int RECORD_PAUSE = 3;
}
